package com.zaoke.web.service.user.impl;

import java.util.Date;
import java.util.Random;

import com.zaoke.web.bo.user.Ticket;
import com.zaoke.web.bo.user.User;
import com.zaoke.web.dao.ticket.TicketDao;
import com.zaoke.web.service.user.TicketService;

public class TicketServiceImpl implements TicketService{

	private TicketDao ticketDao;

	public Ticket generateTicket(User user) {
		Ticket ticket = null;
		if(user != null){
			ticket = new Ticket();
			ticket.setTicket(genTicket());
			ticket.setUserId(user.getUserId());
			ticket.setAddUserId(user.getUserId());
			ticket.setAddTime(new Date());
			
			ticketDao.addTicket(ticket);
		}
		return ticket;
	}
	
	private String genTicket() {
		return getRandString(20);
	}
	
    private final char[] CODE_ARRAY = { '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

    public String getRandString(int length) {
	    Random rand = new Random();
	    StringBuffer sb = new StringBuffer();
	    for (int i = 0; i < length; i++) {
	        sb.append(CODE_ARRAY[rand.nextInt(CODE_ARRAY.length)]);
	    }
	    return sb.toString();
    }

	public Ticket getUserTicket(long userid, String ticket){
		return ticketDao.getTicketByUser(userid, ticket);
	}

	public TicketDao getTicketDao() {
		return ticketDao;
	}

	public void setTicketDao(TicketDao ticketDao) {
		this.ticketDao = ticketDao;
	}

}
